package com.tianheng.wanzhou.datacollecting.netty.yxdzhengjing;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.KaiyuanZhengjing;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IKaiyuanZhengjingService;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import com.tianheng.wanzhou.datacollecting.util.TqlHexchange;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component(value = "yxdzhengjingHandler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IKaiyuanZhengjingService kaiyuanZhengjingService;
    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();


    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        kaiyuanZhengjingService = this.kaiyuanZhengjingService;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 0).eq("status", 1).eq("son_type", "04");
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            KaiyuanZhengjing kaiyuanZhengjing = new KaiyuanZhengjing();
            kaiyuanZhengjing.setMachineIp(machine.getMacIp());
            kaiyuanZhengjing.setMachineId(machine.getMacId());
            if (str.length() == 406 && str.substring(0,12).equals("686F6F680200")){
                kaiyuanZhengjing.setSetLength(TqlHexchange.zcInt(str.substring(314,318)));
                kaiyuanZhengjing.setActualLength(TqlHexchange.zcInt(str.substring(394,402))/10);
                kaiyuanZhengjing.setSetSpeed(TqlHexchange.zcInt(str.substring(326,330)));
                kaiyuanZhengjing.setActualWarpNum(TqlHexchange.zcInt(str.substring(338,342)));
                kaiyuanZhengjing.setDuantou(TqlHexchange.zcInt(str.substring(342,346)));
                kaiyuanZhengjing.setActualSpeed(TqlHexchange.zcInt(str.substring(382,386)));
                kaiyuanZhengjing.setDuantoulv(TqlHexchange.zcInt(str.substring(370,374)));

                kaiyuanZhengjingService.saveOrUpdate(kaiyuanZhengjing);
                ctx.channel().close();
                ctx.close();


            }

        }finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
